import {
	defineStore
} from 'pinia';
import {
	login
} from '@/api/user';
import {
	setToken,
	getToken,
	removeToken
} from '@/utils/token';
import {
	setStorage,
	getStorage
} from '@/utils/storageData';
import {
	handRouterTable,
	handMenuData
} from '@/utils/router';
const projectName = 'enterprise_admin';
export const useUserStore = defineStore('main', {
	state: () => {
		return {
			token: getToken('token'),
			errorImg: 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png',
			menus: getStorage('menus'),
			renderMenus: getStorage('renderMenus'),
			userInfo: getStorage('userInfo'),
			list: {},
		};
	},
	getters: {

	},
	actions: {
		bus_on(name, fn) {
			let self = this;
			self.list[name] = self.list[name] || [];
			self.list[name].push(fn);
		},
		// 发布
		bus_emit(name, data) {
			let self = this;
			if (self.list[name]) {
				self.list[name].forEach((fn) => {
					fn(data);
				});
			}
		},
		// 取消订阅
		bus_off(name) {
			let self = this;
			if (self.list[name]) {
				delete self.list[name];
			}
		},
		/**
		 * @description 登录
		 * @param {*} token
		 */
		async afterLogin(info) {
			let self = this;
			self.userInfo = self.userInfo || {};
			const {data} = await login(info);
			console.log(data);
			setToken(data.token || 'token', 'token');
			const menus = [];
			let renderMenusList = handMenuData(JSON.parse(JSON.stringify(menus)));
			let menusList = handRouterTable(JSON.parse(JSON.stringify(menus)));
			setStorage(JSON.stringify(menusList), 'menus');
			setStorage(JSON.stringify(renderMenusList), 'renderMenus');
			self.userInfo.username = data.user_name || data;
			setStorage(JSON.stringify(self.userInfo), 'userInfo');
			self.token = data.token || 'token';
			console.log(self.token);
			self.menus = menusList;
			self.renderMenus = renderMenusList;
			console.log('login');
		},
		/**
		 * @description 退出登录
		 * @param {*} token
		 */
		afterLogout() {
			let self = this;
			removeToken();
			self.token = null;
			self.menus = null;
			console.log('removeToken');
		},
	}
});
export default useUserStore;